<?php
namespace Home\Service;

/**
 * VoteService
 */
class VoteService extends CommonService {
    /**
     * 添加
     * @param  array vote 投票选项
     * @return array
     */
    public function add($vote) {
        $Vote = $this->getD();

        $Vote->startTrans();
        if (false === ($vote = $Vote->create($vote))) {
            return $this->errorResultReturn($Vote->getError());
        }
        $as = $Vote->add($vote);

        if (false === $as) {
            $Vote->rollback();
            return $this->errorResultReturn('系统出错了！');
        }

        $Vote->commit();
        return $this->resultReturn(true);
    }

    /**
     * 更新投票选项信息
     * @return
     */
    public function update($vote) {
        $Vote = $this->getD();

        if (false === ($vote = $Vote->create($vote))) {
            return $this->errorResultReturn($Vote->getError());
        }

        if (false === $Vote->save($vote)) {
            return $this->errorResultReturn('系统错误！');
        }
        
        return $this->resultReturn(true);
    }

    /**
     *删除投票选项信息
     *@return
     */
    public function delete($id) {
        $Vote = $this->getD();
        
        $Vote->startTrans();
        $delstate = $Vote->delete($id);
        if (false === $delstate) {
            $Vote->rollback();
            return $this->resultReturn(false);
        }
        $Vote->commit();
        
        return $this->resultReturn(true);
    }

    /**
	 *排序
	 *@return
	 */
	public function sort($sortid,$sort) {
		$Vote = $this->getD();
		
		$Vote->startTrans();
		for ($i = 0; $i <= count($sortid); $i++) {
			$Vote->where('id='.intval($sortid[$i]))->setField('sort',intval($sort[$i]));
		}
		$Vote->commit();
		
		return $this->resultReturn(true);
	}

    /**
     * 是否存在投票选项
     * @param  int     $id 投票选项id
     * @return boolean
     */
    public function existVote($id) {
        return !is_null($this->getM()->getById($id));
    }

    protected function getModelName() {
        return 'Vote';
    }
}
